﻿using System;
using System.Collections.Generic;
using System.Text;
using jscc.Ast;

namespace jscc.CodeGen
{
    public class JsConstructor : JsMethod
    {
        public JsConstructor(AstConstructor method) 
            : base(method)
        {
        }

        public override void Write(CodeWriter writer)
        {
            AstClass klass = ast.Parent as AstClass;

            // TODO: Error
            if(klass == null) return;

            writer.Write("this.");
            writer.Write(klass.Name);
            writer.Write(" = function(");
            writer.Write(klass.Params);
            writer.Write(")");
        }

        public override void WriteEnd(CodeWriter writer)
        {
            AstClass klass = ast.Parent as AstClass;

            // TODO: Error
            if(klass == null) return;

            writer.Write("if(");
            writer.Write(klass.Name);
            writer.Write("._init) return;");
            writer.WriteLineEnd();

            writer.Write("this.");
            writer.Write(klass.Name);
            writer.Write("(");
            writer.Write(klass.Params);
            writer.Write(");");
            writer.WriteLineEnd();
            /*base.WriteEnd(writer);

            AstClass parent = this.ast.Parent as AstClass;

            // TODO: Error
            if(parent == null) return;

            writer.Write("this.");
            writer.Write(parent.Name);
            writer.Write("();");
            writer.WriteLineEnd();*/
        }
    }
}
